/**
 * 
 */
define(function(){
	function addconsolelog(str, jsonobj) {
		if (jsonobj) {
			$SC.addconsolelog("[ctiextra_recordctidata]" + str + ", " + JSON.stringify(jsonobj));
		} else {
			$SC.addconsolelog("[ctiextra_recordctidata]" + str);
		}
	}

	var CRecord = {
		createNew: function() {
			const record = {};
			record.recordGuid = '';
			record.epid = '';
			record.dnis = '';
			record.dnismask = '';
			record.dnisenc = '';
			record.ani = '';
			record.animask = '';
			record.anienc = '';
			record.startTime = '';
			record.endTime = '';
			record.callStartTime = '';
			record.agentId = '';
			record.extension = '';
			record.hostName = '';
			record.callType = 0;
			record.hangupType = 0;
			record.documentPath = ''
			record.fileFormat = 0;
			record.initCallId = '';
			record.recordNo = 0;

			record.businessType1 = '';
			record.businessType2 = '';
			record.stringField1 = '';
			record.stringField2 = '';
			record.stringField3 = '';
			record.stringField4 = '';
			record.stringField5 = '';
			record.stringField6 = '';
			record.stringField7 = '';
			record.stringField8 = '';
			record.stringField9 = '';
			record.stringField10 = '';

			record.eventGuid = '';
			record.customerGuid = '';
			record.customerName = '';
			record.staffId = '';
			record.rolegroupId = '';
			record.mProjectId = '';

			record._dirtyFlag = 0;
			record._saveFlag = 0;
			record._recording = 0;

			return record;
		}
	}

	var m_guid = "",
		m_UCID = "",
		m_url = undefined,
		m_format = 0,
		m_recdat = "ucid",
		m_bUserData = true,
		m_recData = '',
		m_recstrfield2 = "",
		m_recdats = [m_recdat],
		m_otherfields = {},
		m_sqlkey_record_insert = "",
		m_sqlkey_record_update = "",
		m_autorecordno = true,
		m_rec;
	
	var Extra = function(project, params){
		this.project = project;
		this.name = "ctiextra_recordctidata";
		m_url = project.getParam("RECURL");
		m_format = project.getParam("RECFMT") || 0;
		m_recdat = project.getParam("RECDAT");
		if (m_recdat.startsWith('\\')) {
			m_bUserData = false;
			m_recdat = m_recdat.substring(1).toLowerCase();
		}
		if (!m_recdat) {
			m_recdat = "ucid";
			m_recdats = [m_recdat];
		} else {
			m_recdats = m_recdat.split("|");
		}
		m_recstrfield2 = project.getParam("RECST2");
		addconsolelog('getParam', {'RECURL': m_url, 'RECDAT': m_recdat, 'RECST2': m_recstrfield2});
		$SC.regcall(this.name, [["queryextra", this.queryCTICall]], params);
		$SC.addEvtListener(this.name, "OnSCTIEvent", OnSCTIEvent, -1, params);
		$SC.addEvtListener(this.name, "OnOrigCTIEvent", OnCTIEvent, -1, params);
	}
	Extra.prototype = {
		queryCTICall: function (callName, callParams, callback) {
			if (callName.toLowerCase() === "queryextra" && callParams.callname === "setrecord") {
				var props = callParams.params.split("|");
				for (let i = 0; i < props.length; i++) {
					var oneprop = props[i].split("=");
					if (oneprop.length > 1) {
						switch (oneprop[0].toLowerCase()) {
							case "record_guid":
								break;
							case "bussinesstype1" :
							case "businesstype1":
								m_otherfields.businesstype1 = oneprop[1];
								break;
							case "bussinesstype2" :
							case "businesstype2":
								m_otherfields.businesstype2 = oneprop[1];
								break;
							case "stringfield1" :
								addconsolelog("stringfield1 is used for ctiType");
								break;
							case "stringfield2":
							case "stringfield3":
							case "stringfield4":
							case "stringfield5":
							case "stringfield6":
							case "stringfield7":
							case "stringfield8":
							case "stringfield9":
							case "stringfield10":
								m_otherfields[oneprop[0].toLowerCase()] = oneprop[1];
								break;
							default :
								addconsolelog("unsupported setrecord field " + oneprop[0]);
								break;
						}
					}
				}
				OnSCTIEvent("setrecord");
			}
		}
	}

	function OnCTIEvent(evt) {
		try {
			var e = evt.event.value.toString().toLowerCase();
			switch (e) {
				case '1':
				case '2':
				case '3':
					if (m_bUserData === false) {
						if (evt[m_recdat]) {
							m_recData = evt[m_recdat].value;
						}
					}
					break;
				default:
			}
		} catch (e) {

		}
	}

	function OnSCTIEvent(evt){
		switch(evt.toLowerCase()){
			case "onlogin":
				m_sqlkey_record_insert = $SC._getconfig("CTISave", "sqlkey_record_insert") || "softphone.extra.record.insert.v202008";
				m_sqlkey_record_update = $SC._getconfig("CTISave", "sqlkey_record_update") || "softphone.extra.record.update.v202008";
				if (m_sqlkey_record_insert >= "softphone.extra.record.insert.v202008") {
					m_autorecordno = true;
				}
				m_recfmt = $SC._getconfig("RECORD", "RECFMT");
				if (m_recfmt != undefined) {
					m_format = m_recfmt;
				}
				if (!m_format) {
					m_format = 0;
				}
				break;
			case "oncallstart":
				m_guid = "";
				m_UCID = "";
				m_recData = "";
				if (!m_url) {
					m_url = "";
				}
				m_rec = undefined;

				break;
			case "oncallestablish":
		//softphone.extra.record.insert.v201610=INSERT INTO Record{C1}(Record_GUID,DNIS,ANI,StartTime,EndTime,Staff_ID,Agent_ID,Extension,HostName,CallType,HangupType,DocumentPath,FileFormat,Rolegroup_ID,MProject_ID,Customer_GUID,CustomerName,InitCallID,Event_GUID) values(@{C2}S,@{C3}S,@{C4}S,@{C5}D,@{C6}D,@{C7}S,@{C8}S,@{C9}S,@{C10}S,@{C11}N,@{C12}N,@{C13}S,@{C14}N,@{C15}S,@{C16}S,@{C17}S,@{C18}S,@{C19}S,@{C20}S)
		//softphone.extra.record.insert.v201610=INSERT INTO Record{C1}(Record_GUID,DNIS,ANI,StartTime,EndTime,Staff_ID,Agent_ID,Extension,HostName,CallType,HangupType,DocumentPath,FileFormat,Rolegroup_ID,MProject_ID,Customer_GUID,CustomerName,InitCallID,Event_GUID,Objective_GUID,dynfield1,dynfield2,dynfield3,dynfield4,dynfield5) values(@{C2}S,@{C3}S,@{C4}S,@{C5}D,@{C6}D,@{C7}S,@{C8}S,@{C9}S,@{C10}S,@{C11}N,@{C12}N,@{C13}S,@{C14}N,@{C15}S,@{C16}S,@{C17}S,@{C18}S,@{C19}S,@{C20}S,@{C21}S,@{C22}@,@{C23}S,@{C24}S,@{C25}S,@{C26}S)
				m_otherfields = {};
				m_otherfields.stringfield1 = $SC.ctiType;
				m_guid = Guid.raw();


				//m_UCID = $SC.CallInfo.AttachData("ucid");
				if (m_bUserData === false) {
					m_UCID = m_recData;
				} else {
					if (m_recdats.length > 0) {
						for (var i=0; i<m_recdats.length; i++)
						{
							m_UCID = $SC.CallInfo.AttachData(m_recdats[i]);
							if (m_UCID) {
								break;
							}
						}
					}
					if (!m_UCID && m_recdats.length <=1 && m_recdat.toLowerCase() != "ucid") {
						m_UCID = $SC.CallInfo.AttachData("ucid");
					}
				}

				var str2 = "";
				if (m_recstrfield2) {
					str2 = $SC.CallInfo.AttachData(m_recstrfield2);
					if (str2) {
						m_otherfields.stringfield2 = str2;
					}
				}

				var mproject_id = $E.getActiveProject().id;
				if (mproject_id.length > 6) {
					mproject_id = mproject_id.substr(0, 6);
				}
				var recordno = 0;
				//if ($E.getActiveProject().dbtype.__default__ == "ORACLE") {
				if (!m_autorecordno) {
					if ($E.getActiveProject().getDbType() == "ORACLE") {
						try {
							var r = $SC.executeselectsql("softphone.extra.record.recordno.v201610");
							if (r.code >0) {
								recordno = r.value[0].fields[0][0];
							}
						} catch (err) {

						}
					}
				}
				if (!m_otherfields.businesstype1 || m_otherfields.businesstype1 == "undefined") {
					m_otherfields.businesstype1 = "";
				}
				if (!m_otherfields.businesstype2 || m_otherfields.businesstype2 == "undefined") {
					m_otherfields.businesstype2 = "";
				}
				if (!m_otherfields.stringfield1 || m_otherfields.stringfield1 == "undefined") {
					m_otherfields.stringfield1 = "";
				}
				if (!m_otherfields.stringfield2 || m_otherfields.stringfield2 == "undefined") {
					m_otherfields.stringfield2 = "";
				}
				if (!m_otherfields.stringfield3 || m_otherfields.stringfield3 == "undefined") {
					m_otherfields.stringfield3 = "";
				}
				if (!m_otherfields.stringfield4 || m_otherfields.stringfield4 == "undefined") {
					m_otherfields.stringfield4 = "";
				}
				if (!m_otherfields.stringfield5 || m_otherfields.stringfield5 == "undefined") {
					m_otherfields.stringfield5 = "";
				}
				if (!m_otherfields.stringfield6 || m_otherfields.stringfield6 == "undefined") {
					m_otherfields.stringfield6 = "";
				}
				if (!m_otherfields.stringfield7 || m_otherfields.stringfield7 == "undefined") {
					m_otherfields.stringfield7 = "";
				}
				if (!m_otherfields.stringfield8 || m_otherfields.stringfield8 == "undefined") {
					m_otherfields.stringfield8 = "";
				}
				if (!m_otherfields.stringfield9 || m_otherfields.stringfield9 == "undefined") {
					m_otherfields.stringfield9 = "";
				}
				if (!m_otherfields.stringfield10 || m_otherfields.stringfield10 == "undefined") {
					m_otherfields.stringfield10 = "";
				}

				m_rec = CRecord.createNew();
				m_rec.recordGuid = m_guid;
				m_rec.recordNo = recordno;
				m_rec.stringField1 = $SC.ctiType;
				m_rec.agentId = $SC.agentId;
				m_rec.extension = $SC.dn;
				m_rec.staffId = $E.staff.id;
				m_rec.rolegroupId = $E.staff.current.groupId;
				m_rec.mProjectId = mproject_id;
				m_rec.businessType1 = m_otherfields.businesstype1;
				m_rec.businessType2 = m_otherfields.businesstype2;
				//m_rec.stringField1 = m_otherfields.stringfield1;
				m_rec.stringField2 = m_otherfields.stringfield2 || '';
				m_rec.stringField3 = m_otherfields.stringfield3 || '';
				m_rec.stringField4 = m_otherfields.stringfield4 || '';
				m_rec.stringField5 = m_otherfields.stringfield5 || '';
				m_rec.stringField6 = m_otherfields.stringfield6 || '';
				m_rec.stringField7 = m_otherfields.stringfield7 || '';
				m_rec.stringField8 = m_otherfields.stringfield8 || '';
				m_rec.stringField9 = m_otherfields.stringfield9 || '';
				m_rec.stringField10 = m_otherfields.stringfield10 || '';

				m_rec.ani = $SC.CallInfo.ANI;
				m_rec.animask = $SC.getdbmask(m_rec.ani, 'record', 'ani');
				m_rec.anienc = $SC.getdbenc(m_rec.ani);
				m_rec.dnis = $SC.CallInfo.DNIS;
				m_rec.dnismask = $SC.getdbmask(m_rec.dnis, 'record', 'dnis');
				m_rec.dnisenc = $SC.getdbenc(m_rec.dnis);
				m_rec.startTime = $SC.CallInfo.EstablishTime;
				m_rec.endTime = $SC.CallInfo.EndTime;
				m_rec.callStartTime = $SC.CallInfo.StartTime;
				m_rec.hangupType = parseInt($SC.CallInfo.hangupType) || 0;
				m_rec.callType = ($SC.CallInfo.CallType == "3") ? 2 : 1
				m_rec.documentPath = replaceRecPath(m_url);
				m_rec.eventGuid = $SC.CallInfo.Event_GUID;
				m_rec.customerGuid = $SC.CallInfo.m_Event.customer_guid || '';
				m_rec.customerName = $SC.CallInfo.m_Event.customername || '';
				m_rec._recording = 1;

				$SC.executeupdatesql(m_sqlkey_record_insert, [m_rec.epid, m_rec.recordGuid, m_rec.dnismask, m_rec.animask, m_rec.startTime, m_rec.endTime
					, m_rec.staffId, m_rec.agentId, m_rec.extension, m_rec.hostName, m_rec.callType
					, m_rec.hangupType, m_rec.documentPath, m_rec.fileFormat
					, m_rec.rolegroupId, m_rec.mProjectId, m_rec.customerGuid, m_rec.customerName
					, m_rec.initCallId, m_rec.eventGuid, m_rec.recordNo, m_rec.anienc, m_rec.dnisenc
					, m_rec.businessType1, m_rec.businessType2, m_rec.stringField1, m_rec.stringField2
					, m_rec.stringField3, m_rec.stringField4, m_rec.stringField5, m_rec.stringField6, m_rec.stringField7
					, m_rec.stringField8, m_rec.stringField9, m_rec.stringField10, m_rec.callStartTime]);

				//$SC.executeupdatesql("softphone.extra.record.insert.v201610", [$E.staff.epidSql, m_guid, $SC.getdbmask($SC.CallInfo.DNIS, "record", "dnis"), $SC.getdbmask($SC.CallInfo.ANI, "record", "ani"), $SC.CallInfo.EstablishTime, $SC.CallInfo.EndTime
				//$SC.executeupdatesql(m_sqlkey_record_insert, [$E.staff.epidSql, m_guid, $SC.getdbmask($SC.CallInfo.DNIS, "record", "dnis"), $SC.getdbmask($SC.CallInfo.ANI, "record", "ani"), $SC.CallInfo.EstablishTime, $SC.CallInfo.EndTime
				//		, $E.staff.id, $SC.agentId, $SC.dn, "", ($SC.CallInfo.CallType == "3") ? 2 : 1
				//		, $SC.CallInfo.hangupType, replaceRecPath(m_url), m_format
				//		, $E.staff.current.groupId, mproject_id, $SC.CallInfo.m_Event.customer_guid, $SC.CallInfo.m_Event.customername
				//		, m_UCID, $SC.CallInfo.Event_GUID, recordno, $SC.getdbenc($SC.CallInfo.ANI), $SC.getdbenc($SC.CallInfo.DNIS)
				//		, m_otherfields.businesstype1, m_otherfields.businesstype2,m_otherfields.stringfield1,m_otherfields.stringfield2
				//		,m_otherfields.stringfield3,m_otherfields.stringfield4,m_otherfields.stringfield5,m_otherfields.stringfield6,m_otherfields.stringfield7
				//		,m_otherfields.stringfield8,m_otherfields.stringfield9,,m_otherfields.stringfield10,$SC.CallInfo.StartTime]);
				$SC.setRecordInfo({recording_guid : m_rec.recordGuid, recording_state : m_rec._recording, recording_file : m_rec.documentPath, recording_starttime: m_rec.startTime, recording_endtime: m_rec.endTime});
				break;
			case "oncallend":
			case "saveevent":
			case "setrecord":
		//softphone.extra.record.update=update Record{C1} set DNIS=@{C3}S,ANI=@{C4}S,StartTime=@{C5}D,EndTime=@{C6}D,CallType=@{C7}S,HangupType=@{C8}N,DocumentPath=@{C9}S,InitialCallID=@{C10}S,Customer_GUID=@{C11}S,CustomerName=@{C12}S,Event_GUID=@{C13}S where record_guid=@{C2}S
		//softphone.extra.record.update=update Record{C1} set DNIS=@{C3}S,ANI=@{C4}S,StartTime=@{C5}D,EndTime=@{C6}D,CallType=@{C7}S,HangupType=@{C8}N,DocumentPath=@{C9}S,InitialCallID=@{C10}S,Customer_GUID=@{C11}S,CustomerName=@{C12}S,Event_GUID=@{C13}S,Objective_GUID=@{C14}S,dynfield1=@{C15}S,dynfield2=@{C16}S,dynfield3=@{C17}S,dynfield4=@{C18}S,dynfield5=@{C19}S where record_guid=@{C2}S
//softphone.extra.record.insert.v202008=INSERT INTO Record{C1}(Record_GUID,DNIS,ANI,StartTime,EndTime,Staff_ID,Agent_ID,Extension,HostName,CallType,HangupType,DocumentPath,FileFormat,Rolegroup_ID,MProject_ID,Customer_GUID,CustomerName,InitCallID,Event_GUID,ANI_ENC,DNIS_ENC,BUSSINESSTYPE1,BUSSINESSTYPE2,STRINGFIELD1,STRINGFIELD2) values(@{C2}S,@{C3}S,@{C4}S,@{C5}D,@{C6}D,@{C7}S,@{C8}S,@{C9}S,@{C10}S,@{C11}N,@{C12}N,@{C13}S,@{C14}N,@{C15}S,@{C16}S,@{C17}S,@{C18}S,@{C19}S,@{C20}S,@{C22}S,@{C23}S,@{C24}S,@{C25}S,@{C26}S,@{C27}S)
//softphone.extra.record.update.v202008=update Record{C1} set DNIS=@{C3}S,ANI=@{C4}S,StartTime=@{C5}D,EndTime=@{C6}D,CallType=@{C7}S,HangupType=@{C8}N,DocumentPath=@{C9}S,InitCallID=@{C10}S,Customer_GUID=@{C11}S,CustomerName=@{C12}S,Event_GUID=@{C13}S,BUSSINESSTYPE1=@{C14}S,BUSSINESSTYPE2=@{C15}S,STRINGFIELD1=@{C16}S,STRINGFIELD2=@{C17}S where record_guid=@{C2}S
				if (m_guid) {
					if (m_bUserData === false) {
						m_UCID = m_recData;
					} else {
						if (m_recdats.length > 0) {
							for (var i = 0; i < m_recdats.length; i++) {
								m_UCID = $SC.CallInfo.AttachData(m_recdats[i]);
								if (m_UCID) {
									break;
								}
							}
						}
						if (!m_UCID && m_recdats.length <= 1 && m_recdat.toLowerCase() != "ucid") {
							m_UCID = $SC.CallInfo.AttachData("ucid");
						}
					}

					var str2 = "";
					if (m_recstrfield2) {
						str2 = $SC.CallInfo.AttachData(m_recstrfield2);
						if (str2) {
							m_otherfields.stringfield2 = str2;
						}
					}
					if ($SC.CallInfo.CallState2 === 0) {
						letRecField(m_rec, 'endTime', $SC.CallInfo.EndTime);
					}
					letRecField(m_rec,'initCallId', m_UCID);
					letRecField(m_rec,'stringfield2', m_otherfields.stringfield2);
					//letRecField(m_rec,'endTime', $SC.CallInfo.EndTime);
					letRecField(m_rec,'hangupType', $SC.CallInfo.hangupType);
					letRecField(m_rec,'documentPath', replaceRecPath(m_url));
					letRecField(m_rec, 'customerGuid', $SC.CallInfo.m_Event.customer_guid || '');
					letRecField(m_rec, 'customerName', $SC.CallInfo.m_Event.customername || '');

					if (m_rec._saveFlag === 0 || m_rec._dirtyFlag === 1) {
						m_rec._saveFlag = 1;
						m_rec._dirtyFlag = 0;
						$SC.executeupdatesql(m_sqlkey_record_update, [m_rec.epid, m_rec.recordGuid, m_rec.dnismask, m_rec.animask, m_rec.startTime, m_rec.endTime, m_rec.callType
							, m_rec.hangupType, m_rec.documentPath, m_rec.initCallId, m_rec.customerGuid, m_rec.customerName, m_rec.eventGuid
							, m_rec.businessType1, m_rec.businessType2, m_rec.stringField1, m_rec.stringField2, m_rec.agentId, m_rec.extension, m_rec.initCallId
							, m_rec.stringField3, m_rec.stringField4, m_rec.stringField5, m_rec.stringField6, m_rec.stringField7
							, m_rec.stringField8, m_rec.stringField9, m_rec.stringField10, m_rec.callStartTime]);
					}
					/*
					$SC.executeupdatesql(m_sqlkey_record_update, [$E.staff.epidSql, m_guid, $SC.getdbmask($SC.CallInfo.DNIS, "record", "dnis"), $SC.getdbmask($SC.CallInfo.ANI, "record", "ani"), $SC.CallInfo.EstablishTime, $SC.CallInfo.EndTime, ($SC.CallInfo.CallType == "3") ? 2 : 1
						, $SC.CallInfo.hangupType, replaceRecPath(m_url), m_UCID, $SC.CallInfo.m_Event.customer_guid, $SC.CallInfo.m_Event.customername, $SC.CallInfo.Event_GUID
						, m_otherfields.businesstype1, m_otherfields.businesstype2,m_otherfields.stringfield1,m_otherfields.stringfield2, $SC.agentId, $SC.dn,m_UCID
						,m_otherfields.stringfield3,m_otherfields.stringfield4,m_otherfields.stringfield5,m_otherfields.stringfield6,m_otherfields.stringfield7
						,m_otherfields.stringfield8,m_otherfields.stringfield9,,m_otherfields.stringfield10,$SC.CallInfo.StartTime]);
					 */
					if (evt.toLowerCase === "oncallend") {
						//$SC.setRecordInfo({recording_guid : m_guid, recording_state : ($SC.CallInfo.CallState2 > 0)?1:0, recording_file : replaceRecPath(m_url)});
						m_rec._recording = 0;
						$SC.setRecordInfo({recording_guid : m_rec.recordGuid, recording_state : m_rec._recording, recording_file : m_rec.documentPath, recording_starttime: m_rec.startTime, recording_endtime: m_rec.endTime});
					}
				}
				break;
		}
	}

	function letRecField(rec, fieldName, val) {
		if (rec[fieldName] != val) {
			//console.log('test, fieldName, %s, rec[fieldName], %s, val, %s', fieldName, rec[fieldName], val)
			rec._dirtyFlag = 1;
			rec[fieldName] = val;
		}
	}

	function replaceRecPath(recpath){
		if (recpath) {
			var s = recpath.replace(/\[UCID]/gi, encodeURI(m_UCID));
			s.replace('['+m_recdat+']', m_UCID);
			s = s.replace(/\[StartTime]/gi, $SC.CallInfo.EstablishTime);
			s = s.replace(/\[EndTime]/gi, $SC.CallInfo.EndTime);
			s = s.replace(/\[StartTime.YYYYMMDD]/gi, $SC.CallInfo.EstablishTime.split(" ")[0].replace(/[^0-9]/ig,""));
			s = s.replace(/\[AgentID]/gi, $SC.agentId);
			s = s.replace(/\[Extension]/gi, $SC.dn);
			s = s.replace(/\[CallType]/gi, ($SC.CallInfo.CallType == "3") ? 2 : 1);
			return s;
		} else {
			return "";
		}
	}

	return Extra; 
});

